#include "widget.h"
#include "ui_widget.h"
#include "widget.h"
#include "ui_widget.h"
#include<math.h>
#include<QPainter>
#include<QIcon>
#include<QDebug>
#include <QPen>
#include <QFont>
#include<QLabel>
int Widget::flag2=0;
int Widget::score=0;
int Widget::last_x=0;
int Widget::last_y=0;
int Widget::last_color=-1;
int Widget::flag=0;
int Widget::present_x=0;
int Widget::present_y=0;
int Widget::is_exit_num=0;
int Widget::flag1=0;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //setWindowIcon(QIcon(GAME_ICON_));


    initScene();
    //playGame();

    this->play[0] = new QSound(GAME_BGM_GUANQIA01);
    this->play[1] = new QSound(GAME_BGM_GUANQIA02);
    this->play[2] = new QSound(GAME_BGM_GUANQIA03);
    this->play[3] = new QSound(GAME_BGM_WUJIN);

    //加载所有关卡和模式的背景图
    pix[0].load(GUANQIA1_IMG);
    pix[1].load(GUANQIA2_IMG);
    pix[2].load(GUANQIA3_IMG);
    pix[3].load(WUJIN_IMG);
    pix1.load(ZHU_SCORE);


    //this->isLogin = false;

    this->jieMian(); //界面相关操作
    //this->score = 0;
    this->autoShowGameEndDialog(); //放入update函数中
    //this->me->login->getAllUsers(); //将文件中所有的用户信息读入 放入update函数中
    this->updateScore(); //实时修改分数 放入update函数中
    //this->me->loginUser->score = this->score; //实时修改用户分数 放入update函数中

    //QSound::play(GAME_BGM_GUANQIA01); //播放背景音乐 放入play函数中

}

Widget::~Widget()
{
    delete ui;
}

void Widget::initScene(){
    setWindowTitle(GAME_NAME);//标题
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);//大小
    setWindowIcon(QIcon(GAME_ICON_));
    ui->help->setIconSize(QSize(200,100));
    ui->help->setIcon(QIcon(ZHU_HELP));
        ui->help->setStyleSheet("QPushButton{background-color:rgba(0,0,0,0);}");
       ui->mainMenu->setIconSize(QSize(200,100));
       ui->mainMenu->setIcon(QIcon(ZHU_MENU));
        ui->mainMenu->setStyleSheet("QPushButton{background-color:rgba(0,0,0,0);}");
        ui->again->setIconSize(QSize(200,100));
        ui->again->setIcon(QIcon(ZHU_CHONG));
        ui->again->setStyleSheet("QPushButton{background-color:rgba(0,0,0,0);}");
        ui->end->setIconSize(QSize(200,100));
       ui->end->setIcon(QIcon(ZHU_END));
        ui->end->setStyleSheet("QPushButton{background-color:rgba(0,0,0,0);}");
       ui->me->setIconSize(QSize(200,100));
       ui->me->setIcon(QIcon(ZHU_ME));
        ui->me->setStyleSheet("QPushButton{background-color:rgba(0,0,0,0);}");

}

void Widget::creatBeadposition(){
    int sum = 0;
    for(int i = 0;i < 9; i++){
        for(int j = 0 ;j < 9 ;j++){
            if(!beads[i][j].is_exit){
               sum++;
            }
        }
    }

    while(sum != 0){

        int m = rand()%(PLAID_NUM);
        int n = rand()%(PLAID_NUM);

         if(!beads[m][n].is_exit){
              beads[m][n].Bead_x=m*BEAD_SIZE;
              beads[m][n].Bead_y=n*BEAD_SIZE;
              beads[m][n].is_exit=true;
                 break;
    }
  }

//    while(1){

//        int m = rand()%(PLAID_NUM);
//        int n = rand()%(PLAID_NUM);

//         if(!beads[m][n].is_exit){
//              beads[m][n].Bead_x=m*BEAD_SIZE;
//              beads[m][n].Bead_y=n*BEAD_SIZE;
//              beads[m][n].is_exit=true;
//                 break;
//    }
//  }
}//随机生成珠子


void Widget::creatBeadcolor(){
    for(int i=0;i<PLAID_NUM;i++){
        for(int j=0;j<PLAID_NUM;j++){
            if(beads[i][j].is_exit&&beads[i][j].color==-1){
                 beads[i][j].color=rand()%(COLOR_NUM+guanQia-1);
                switch(beads[i][j].color){
                    case 0: beads[i][j].Bead_pix.load(BEAD_PIX1);break;
                    case 1: beads[i][j].Bead_pix.load(BEAD_PIX2);break;
                    case 2: beads[i][j].Bead_pix.load(BEAD_PIX3);break;
                    case 3: beads[i][j].Bead_pix.load(BEAD_PIX4);break;
                    case 4: beads[i][j].Bead_pix.load(BEAD_PIX5);break;
                    case 5: beads[i][j].Bead_pix.load(BEAD_PIX6);break;
                    case 6: beads[i][j].Bead_pix.load(BEAD_PIX7);break;
                }
        }
    }
}
}

void Widget::disappearBead(int i,int j){
    beads[i][j].is_exit=false;
}//点击初始格子，让格子消失

void Widget::appearBead(int i,int j,int last_color){

    beads[i][j].is_exit=true;
     //qDebug()<<i<<" "<<j;
//     beads[i][j].Bead_x = i*BEAD_SIZE;
//     beads[i][j].Bead_y = j*BEAD_SIZE;
     beads[i][j].color=last_color;
     switch(beads[i][j].color){
         case 0: beads[i][j].Bead_pix.load(BEAD_PIX1);break;
         case 1: beads[i][j].Bead_pix.load(BEAD_PIX2);break;
         case 2: beads[i][j].Bead_pix.load(BEAD_PIX3);break;
         case 3: beads[i][j].Bead_pix.load(BEAD_PIX4);break;
         case 4: beads[i][j].Bead_pix.load(BEAD_PIX5);break;
         case 5: beads[i][j].Bead_pix.load(BEAD_PIX6);break;
         case 6: beads[i][j].Bead_pix.load(BEAD_PIX7);break;

    }//在点击所移坐标处出现珠子
}
void Widget::judgeScore(int score){
    if(score>=GUAN_QIA_2_UNLOCK_SCORE)
    {
        flag1=1;
        //弹出对话框
    }if(GUAN_QIA_3_UNLOCK_SCORE){
        flag2=1;
    }

}

bool Widget::eliminateBeads(int x,int y){//判断五珠相连

    bool f=false;
    int i=1;
    int j=1;
    int sum=1;
   for(i=1;y-i >=0 && beads[x][y-i].color==beads[x][y].color && beads[x][y-i].is_exit;i++){

       sum++;
   }
   for(j=1;y+j <=PLAID_NUM && beads[x][y+j].color==beads[x][y].color&&beads[x][y+j].is_exit;j++){

       sum++;
   }
   if(sum >= 5){
       for(int k=y-i+1;k<=y+j-1;k++){

           beads[x][k].is_exit=false;
           beads[x][k].color=-1;
       }
       QSound::play(":/res/9629.wav");
        score+=1;
       f=true;
   }
sum=1;
   for(i=1;x-i >=0&&beads[x-i][y].color==beads[x][y].color&&beads[x-i][y].is_exit;i++){
       sum++;
   }
   for(j=1;x+j <=PLAID_NUM&&beads[x+j][y].color==beads[x][y].color&&beads[x+j][y].is_exit;j++){
       sum++;
   }
   if(sum>=5){
       for(int k=x-i+1;k<=x+j-1;k++){
           beads[k][y].is_exit=false;
           beads[k][y].color=-1;
//            qDebug()<<"111"<<endl;
       }
       QSound::play(":/res/9629.wav");
        score+=1;
       f=true;

   }
sum=1;
   for(i=1;y-i >=0&&x-i>=0&&beads[x-i][y-i].color==beads[x][y].color&&beads[x-i][y-i].is_exit;i++){
       sum++;
   }
   for(j=1;y+j <=PLAID_NUM&&x+j <=PLAID_NUM&&beads[x+j][y+j].color==beads[x][y].color&&beads[x+j][y+j].is_exit;j++){
       sum++;
   }
   if(sum>=5){
       for(int k= -i+1;k<=j-1;k++){
           beads[x+k][y+k].is_exit=false;
           beads[x+k][y+k].color=-1;
//            qDebug()<<"111"<<endl;
       }
       QSound::play(":/res/9629.wav");
        score+=1;
       f=true;

   }
sum=1;
   for(i=1;y-i >=0&&x+i <=PLAID_NUM&&beads[x+i][y-i].color==beads[x][y].color&&beads[x+i][y-i].is_exit;i++){
       sum++;
   }
   for(j=1;y+j <=PLAID_NUM&&x-j>=0&&beads[x-j][y+j].color==beads[x][y].color&&beads[x-j][y+j].is_exit;j++){
       sum++;
   }
   if(sum>=5){
       for(int k= -i+1;k<=j-1;k++){
           beads[x-k][y+k].is_exit=false;
           beads[x-k][y+k].color=-1;
//            qDebug()<<"111"<<endl;
       }
       QSound::play(":/res/9629.wav");
        score+=1;
       f=true;

   }
   judgeScore(score);
    sum=1;
    return f;
}
void Widget::deleteBeads(){
    for(int i=0;i<PLAID_NUM;i++){
        for(int j=0;j<PLAID_NUM;j++){
            beads[i][j].color=-1;
            beads[i][j].is_exit=false;
            beads[i][j].is_pass=false;
        }
    }

}

void Widget::paintEvent(QPaintEvent *event){
    is_exit_num=0;
   QPainter painter(this);

   //按照关卡和模式绘制背景图
   if(this->isChuangGuanOrWujin){
       if(this->guanQia == 1){
           painter.drawPixmap(0,0,pix[0]);
       }else if(this->guanQia == 2){
           painter.drawPixmap(0, 0, pix[1]);
       }else{
           painter.drawPixmap(0, 0, pix[2]);
       }
   }else{
       painter.drawPixmap(0, 0, pix[3]);
   }
   painter.drawPixmap(490,80,pix1);
   QColor color_(255,255,255);//设置颜色
   QPen pen(color_);
        pen.setWidth(2);
        painter.setPen(pen);
        int x,y;
        for(int i = 0;i <= 9 ;i ++){
            x= 60*i;
             painter.drawLine(x,0,x,540);
        }
        for(int j = 0;j <= 9;j++){
            y = 60*j;
            painter.drawLine(0,y,540,y);

        }





   //painter.drawPixmap(beads[i][j].Bead_x,beads[i][j].Bead_y,beads[i][j].Bead_pix);
   for(int i = 0; i < PLAID_NUM; i++){
       for(int j = 0; j < PLAID_NUM; j++){
           if(beads[i][j].is_exit){
               is_exit_num++;
               painter.drawPixmap(beads[i][j].Bead_x,beads[i][j].Bead_y,beads[i][j].Bead_pix);
               update();
           }
       }
   }

    ui->score->setText(QString::number(this->score));

}
void Widget::mousePressEvent(QMouseEvent *event){

           int x = event->x();
           int y = event->y();
           int x1 = x/BEAD_SIZE;
           int y1 = y/BEAD_SIZE;

          if(flag==0&&beads[x1][y1].is_exit){//判断该格子中是否有珠子
              flag=1;
              last_x=x1;
              last_y=y1;
              //qDebug()<<last_x<<last_y<<endl;
              last_color=beads[x1][y1].color;
              disappearBead(x1,y1);
          }
          else if(flag==1&&!beads[x1][y1].is_exit&& x < CHESSBOARD_SIZE && y < CHESSBOARD_SIZE && seekpath(beads[last_x][last_y],beads[x1][y1])
                  ){
              //qDebug()<<last_x<<last_y<<endl;
               //qDebug()<<x1<<y1<<endl;
              appearBead(x1,y1,last_color);
              if(!eliminateBeads(x1,y1)){
                   defaultGame();
                  for(int i=0;i<ROUNDS_NUM ;i++){
                   creatBeadposition();
                   creatBeadcolor();
                  }
                  eliminateBeads(x1,y1);
              }

              flag=0;
          }
          else if(!seekpath(beads[last_x][last_y],beads[x1][y1])){
              beads[last_x][last_y].is_exit=true;
              beads[last_x][last_y].color=last_color;
              flag=0;
          }
          else{

          }

}
void  Widget::mouseDoubleClickEvent(QMouseEvent *event){
    int x = event->x();
    int y = event->y();
    if(x>=CHESSBOARD_SIZE||y>=CHESSBOARD_SIZE){
        int i=1;
    }
}

void Widget::defaultGame(){
    if(is_exit_num>=78){
        //exit(0);
        //on_end_clicked();
        //this->hide();
        this->egd->show();

    }
}
bool Widget::seekpath(Bead& a,Bead& b){
    int iffind = 0;//是否找到路
    queue<Bead>v;//容器
    Bead c;
    v.push(a);//将初始点插入容器
    while (!v.empty()) {
    c=v.front();//获取最前面的作为查找相邻点的棋子
    v.pop();//删除已取出的点
    if((c.Bead_x/BEAD_SIZE==b.Bead_x/BEAD_SIZE)&&(c.Bead_y/BEAD_SIZE==b.Bead_y/BEAD_SIZE)){//判断该棋子是否为目标棋子
        iffind=1;
        for(int i=0;i<PLAID_NUM;i++){
            for(int j=0;j<PLAID_NUM;j++){
                beads[i][j].is_pass=false;
                beads[i][j].is_pass=false;
            }
        }
        while(!v.empty()){v.pop();}
        return true;
    }
    beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE].is_pass=true;
    if(!beads[c.Bead_x/BEAD_SIZE + 1][c.Bead_y/BEAD_SIZE].is_exit&&
            !beads[c.Bead_x/BEAD_SIZE+1][c.Bead_y/BEAD_SIZE].is_pass
            &&c.Bead_x+BEAD_SIZE<CHESSBOARD_SIZE)
    {  //四个方向的相邻棋子is_exist为false且未经过的棋子可以作为查找的棋子并存入容器
        v.push(beads[c.Bead_x/BEAD_SIZE+1][c.Bead_y/BEAD_SIZE]);
    }
    if(!beads[c.Bead_x/BEAD_SIZE-1][c.Bead_y/BEAD_SIZE].is_exit&&
            !beads[c.Bead_x/BEAD_SIZE-1][c.Bead_y/BEAD_SIZE].is_pass
            &&c.Bead_x-BEAD_SIZE>=0){
        v.push(beads[c.Bead_x/BEAD_SIZE-1][c.Bead_y/BEAD_SIZE]);
    }
    if(!beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE+1].is_exit&&
            !beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE+1].is_pass
            &&c.Bead_y+BEAD_SIZE<CHESSBOARD_SIZE){
        v.push(beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE+1]);
    }
    if(!beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE-1].is_exit&&
            !beads[c.Bead_x/BEAD_SIZE][c.Bead_y/BEAD_SIZE-1].is_pass
            &&c.Bead_y-BEAD_SIZE>=0){
        v.push(beads[c.Bead_x/BEAD_SIZE][(c.Bead_y/BEAD_SIZE)-1]);
    }
    }
    if(iffind == 0){
        for(int i=0;i<PLAID_NUM;i++){
            for(int j=0;j<PLAID_NUM;j++){
                beads[i][j].is_pass=false;
                beads[i][j].is_pass=false;
            }
        }
        while(!v.empty()){v.pop();}
        return false;
   }

}



//判断游戏是否结束的方法
bool Widget::isGameEnd(){
    int flag = 0; //表示珠子的数目
    for(int i = 0; i < 9; i++){
        for(int j = 0; j < 9; j++){
            if(this->beads[i][j].is_exit == true){ //如果存在珠子
                flag++;
            }
        }
    }

    if(flag == 9 * 9){ //如果珠子数等于81
        return true;
    }
    else{
        return false;
    }
}

//自动显示游戏结束对话框
void Widget::autoShowGameEndDialog(){
    if(this->isGameEnd() == true){ //如果游戏结束
        //this->hide(); //隐藏当前窗口
        this->egd->show(); //显示游戏结束对话框
    }
}


void Widget::on_again_clicked()
{
    this->deleteBeads(); //清除全部数据
    //m_time->stop();
    this->playGame();
    this->score = 0;
    ui->score->setText("0");
}

void Widget::on_mainMenu_clicked()
{
    emit showMainMenu(); //发送信号显示主菜单
    //音乐
    if(this->isChuangGuanOrWujin == true){ //闯关模式
        if(this->guanQia == 1){
            this->play[0]->stop();
        }else if(this->guanQia == 2){
            this->play[1]->stop();
        }else{
            this->play[2]->stop();
        }
    }else{
        this->play[3]->stop();
    }

//    this->deleteBeads(); //清除全部数据
//    this->m_time->stop();
    endGame();
    if(this->me->isLogin){
        this->me->isLogin = true;
         QString::number(this->score) = this->me->loginUser->score;
         emit sendChangeScoreInMeUi();
         this->me->loginUser->score = this->score;
         for(int i = 0; i < this->me->users.size(); i++){
             if(this->me->users.at(i)->userName == this->me->loginUser->userName){
                 this->me->users.at(i)->score = this->me->loginUser->score;
                 //this->me->users.at(i) = new User(this->me->loginUser->userName, this->me->loginUser->password, this->me->loginUser->score);
             }
         }
    }

    this->hide(); //隐藏当前窗口

}

void Widget::on_end_clicked()
{
    if(this->me->isLogin){
        this->me->isLogin = true;
         QString::number(this->score) = this->me->loginUser->score;
         emit sendChangeScoreInMeUi();
         this->me->loginUser->score = this->score;
         for(int i = 0; i < this->me->users.size(); i++){
             if(this->me->users.at(i)->userName == this->me->loginUser->userName){
                 this->me->users.at(i)->score = this->me->loginUser->score;
                 //this->me->users.at(i) = new User(this->me->loginUser->userName, this->me->loginUser->password, this->me->loginUser->score);
             }
         }
    }
    this->egd->show(); //显示游戏结束对话框
}

//关闭主窗口
void Widget::closeWidget(){
    this->hide(); //隐藏当前窗口
}

//显示主窗口
void Widget::showWidget(){
    //音乐
    //音乐
    if(this->isChuangGuanOrWujin == true){ //闯关模式
        if(this->guanQia == 1){
            this->play[0]->setLoops(20);
            this->play[0]->play();
        }else if(this->guanQia == 2){
            this->play[1]->setLoops(20);
            this->play[1]->play();
        }else{
            this->play[2]->setLoops(20);
            this->play[2]->play();
        }
    }else{
        this->play[3]->setLoops(20);
        this->play[3]->play();
    }

    playGame();
//    if(this->me->isLogin){
//        this->score = this->me->loginUser->score.toInt();
//        ui->score->setText(QString::number(this->score)); //显示分数
//    }

    this->show(); //显示当前窗口
}

//点击帮助按钮
void Widget::on_help_clicked()
{
     QMessageBox::information(this, HELP_TITLE, HELP);
}

//界面相关操作
void Widget::jieMian(){
    this->isChuangGuanOrWujin = false; //初始化闯关模式或无尽模式判断变量为真
    this->guanQia = 0; //初始化关卡数为0
    this->egd = new EndGameDialog; //新建结束游戏对话框
    this->me = new Me; //新建我对话框
}

void Widget::on_me_clicked()
{
    //音乐
    if(this->isChuangGuanOrWujin == true){ //闯关模式
        if(this->guanQia == 1){
            this->play[0]->stop();
        }else if(this->guanQia == 2){
            this->play[1]->stop();
        }else{
            this->play[2]->stop();
        }
    }else{
        this->play[3]->stop();
    }

    if(this->me->isLogin){
        this->me->isLogin = true;
         QString::number(this->score) = this->me->loginUser->score;
         emit sendChangeScoreInMeUi();
         this->me->loginUser->score = this->score;
         for(int i = 0; i < this->me->users.size(); i++){
             if(this->me->users.at(i)->userName == this->me->loginUser->userName){
                 this->me->users.at(i)->score = this->me->loginUser->score;
                 //this->me->users.at(i) = new User(this->me->loginUser->userName, this->me->loginUser->password, this->me->loginUser->score);
             }
         }
    }
    emit this->showMe(); //发送信号显示我窗口
    this->hide(); //隐藏当前窗口
    //this->me->tempScore = this->score; //传递分数给我界面作为临时分数
}

//实时修改分数
void Widget::updateScore(){
    //添加
}

//接收我界面发送的分数
void Widget::recChangeScoreInMainWidget(){
    if(this->me->isLogin){
        this->me->isLogin = true;
         QString::number(this->score) = this->me->loginUser->score;
         ui->score->setText(QString(this->score));
    }

}

//模式和关卡选择
void Widget::moShiAndGuanQiaChoose(){
    //音乐
    if(this->isChuangGuanOrWujin == true){ //闯关模式
        if(this->guanQia == 1){
            this->play[0]->setLoops(20);
            this->play[0]->play();
            this->deleteBeads();
            this->score = 0;
            ui->score->setText("0");
            QFont ft;
            ft.setPointSize(24);
            ui->score->setFont(ft);
            ui->score->setStyleSheet(
                                     "color: rgb(255, 255, 0)");

            this->playGame();
        }else if(this->guanQia == 2){
            this->play[1]->setLoops(20);
            this->play[1]->play();
            this->deleteBeads();
            this->score = 0;
            ui->score->setText("0");
            QFont ft;
            ft.setPointSize(24);
            ui->score->setFont(ft);
            ui->score->setStyleSheet(
                                     "color: rgb(255, 255, 0)");
            this->playGame();
        }else{
            this->play[2]->setLoops(20);
            this->play[2]->play();
            this->deleteBeads();
            this->score = 0;
            ui->score->setText("0");
            QFont ft;
            ft.setPointSize(24);
            ui->score->setFont(ft);
            ui->score->setStyleSheet(
                                     "color: rgb(255, 255, 0)");
            this->playGame();
        }
    }else{
        this->play[3]->setLoops(20);
        this->play[3]->play();
        this->deleteBeads();
        this->score = 0;
        ui->score->setText("0");
        QFont ft;
        ft.setPointSize(24);
        ui->score->setFont(ft);
        ui->score->setStyleSheet(
                                 "color: rgb(255, 255, 0)");
        this->playGame();
    }
}

//接收模式选择完成信号
void Widget::recMoShi(){
    this->moShiAndGuanQiaChoose();
}

void Widget::endMusic(){
    //音乐
    if(this->isChuangGuanOrWujin == true){ //闯关模式
        if(this->guanQia == 1){
            this->play[0]->stop();
        }else if(this->guanQia == 2){
            this->play[1]->stop();
        }else{
            this->play[2]->stop();
        }
    }else{
        this->play[3]->stop();
    }
}

//开始游戏
void Widget::playGame(){

    for(int i=0;i<PLAID_NUM;i++){
        for(int j=0;j<PLAID_NUM;j++){
            beads[i][j].Bead_x=i*BEAD_SIZE;
            beads[i][j].Bead_y=j*BEAD_SIZE;
        }
    }

    srand((unsigned int )(time(NULL)));
    for(int i=0;i<FIRST_ROUND_NUM;i++){
        creatBeadposition();
        creatBeadcolor();
    }
    m_time = new QTimer(this);
    m_time->setInterval(10);
    m_time->start();
    connect(m_time, &QTimer::timeout, [=](){
        //this->autoShowGameEndDialog();
        update();
    });
//    if(beads[i][j].is_exit){
//        Bead_rect.setWidth(Bead_pix.width());
//        Bead_rect.setHeight(Bead_pix.height());
//        Bead_rect.moveTo(Bead_x,Bead_y);
//    }
}

void Widget::endGame(){
    this->deleteBeads(); //清除全部数据
    this->score = 0;
    ui->score->setText("0");
    QFont ft;
    ft.setPointSize(24);
    ui->score->setFont(ft);
    ui->score->setStyleSheet(
                             "color: rgb(255, 255, 0)");
    //ui->score->set
    //this->deleteBeads();
    this->m_time->stop();
    this->playGame();
}
